package com.gykfbxxh.imovie.view.filmsdetail.view;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.adapter.FilmCommentAdapter;
import com.gykfbxxh.imovie.bean.comment.FilmComment;
import com.gykfbxxh.imovie.bean.comment.FilmCommentBean;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.view.LoadMoreView;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.utils.HttpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 加载评论的listview
 * Created by xuxinghai on 2017/09/05.
 */
public class CommentListView extends ListView implements AbsListView.OnScrollListener, View.OnClickListener {

    //控件变量
    LoadMoreView loadMoreView;//加在更多的view

    //逻辑变量
    private boolean isRefreshing;//是否正在刷新
    private int mDataPage = 1;//当前页数
    private String fObjectid;//id
    private Activity mActivity;
    private String mRequestName;//请求标识
    private boolean isAutoLoadMore = true;//是否自动加载下一页
//    private int addCommentIndex;//添加评论下标

    private List<FilmComment> mCommentList;//新闻评论集合
    //适配器
    private FilmCommentAdapter mCommentAdapter;//评论适配器

    public CommentListView(Context context) {
        super(context);
        initView(context);
    }

    public CommentListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public CommentListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    /**
     * 初始化配置view
     *
     * @param context
     */
    private void initView(Context context) {
        setVerticalScrollBarEnabled(true);
        loadMoreView = new LoadMoreView(context);
        loadMoreView.setErrorPageOnClickListener(this);
        addFooterView(loadMoreView);
        this.setOnScrollListener(this);
    }


    /**
     * 开始加载数据
     *
     * @param activity
     */
    public void startLoadData(Activity activity, String fObjectid, String requestName) {
        if (activity == null || activity.isFinishing()) {
            return;
        }
        this.mActivity = activity;
        this.fObjectid = fObjectid;
        this.mRequestName = requestName;
        //加载数据
        mDataPage = 1;
//        addCommentIndex = 0;
        loadCommentData();
    }


    /**
     * 重置数据
     *
     * @param activity
     * @param fObjectid
     */
    public void startResetData(Activity activity, String fObjectid, String requestName) {
        if (activity == null || activity.isFinishing()) {
            return;
        }
        this.mActivity = activity;
        this.fObjectid = fObjectid;
        this.mRequestName = requestName;
        if (mCommentList == null) {
            mCommentList = new ArrayList<FilmComment>();
        } else {
            mCommentList.clear();
        }
        if (mCommentAdapter == null) {
            mCommentAdapter = new FilmCommentAdapter(mCommentList, mActivity);
        }
        if (getAdapter() == null) {
            setAdapter(mCommentAdapter);
        } else {
            mCommentAdapter.notifyDataSetChanged();
        }
        //加载数据
        mDataPage = 1;
        loadCommentData();
    }

    /**
     * 设置刷新中
     *
     * @param msg
     */
    public void onRefreshing(String msg) {
        if (this.loadMoreView != null) {
            this.loadMoreView.showLoading(msg);
            this.isRefreshing = true;
        }
    }

    /**
     * 刷新完成
     */
    private void onComplete(int type, String msg) {
        if (this.loadMoreView != null) {
            switch (type) {
                case 1://加载成功
                    this.loadMoreView.showSuccess();
                    break;
                case 2://加载错误
                    this.loadMoreView.showErrorPage(msg);
                    break;
                case 3://空数据
                    this.loadMoreView.showEmptyPage();
                    break;
            }

            this.isRefreshing = false;
        }
    }

    /**
     * 设置底部背景颜色
     *
     * @param resourceId
     */
    public void setFootViewColor(int resourceId) {
        if (loadMoreView != null) {
            loadMoreView.setBackgroundColor(getResources().getColor(resourceId));
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        //当滑动停止并且滑动到底部时加载更多数据
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            if (view.getLastVisiblePosition() >= (view.getCount() - 2)) {
                onRefreshMore();
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }

    /**
     * 加载更多
     */
    public void onRefreshMore() {
        if (isRefreshing() || !isAutoLoadMore) {
            return;
        }
        mDataPage++;
        loadCommentData();
    }

    /**
     * 加载评论
     */
    private void loadCommentData() {
        if (TextUtils.isEmpty(fObjectid)) {
            return;
        }

        if (mCommentList == null) {
            mCommentList = new ArrayList<FilmComment>();
        }
        if(mCommentList.size()>0) {
            FilmComment filmComment = mCommentList.get(0);
            if(TextUtils.isEmpty(filmComment.getCommentTypeName())) {
                FilmComment newsComment = new FilmComment();
                newsComment.setCommentTypeName("评论");
                mCommentList.add(newsComment);
            }
        }else {
            //只配置一个最新评论的title
            FilmComment newsComment = new FilmComment();
            newsComment.setCommentTypeName("评论");
            mCommentList.add(newsComment);
        }
        if (mCommentAdapter == null) {
            mCommentAdapter = new FilmCommentAdapter(mCommentList, mActivity);
            setAdapter(mCommentAdapter);
        }
        mCommentAdapter.notifyDataSetChanged();
        HttpUtils.addGetRequest(URIContant.GETCOMMENTLIST + fObjectid+"&pno="+mDataPage, new TypeToken<FilmCommentBean>() {
        }.getType(), "FilmDetailActivity", new HttpListener<FilmCommentBean>() {
            @Override
            public void onStart() {
                //设置正在刷新
                onRefreshing(null);
            }

            @Override
            public void onError(VolleyError error) {
                //设置刷新状态
                onComplete(2,null);
            }

            @Override
            public void onSuccess(FilmCommentBean response) {
                int  type;
                String msg = null;
                if (response!=null&&response.getResult()!=null) {

                    FilmCommentBean.FilmCommentResult result = response.getResult();
                    List<FilmComment> list = result.getList();

                    if (list != null && list.size() > 0) {
                        mCommentList.addAll(list);
                        mCommentAdapter.notifyDataSetChanged();
                        type = 1;
                        isAutoLoadMore = true;
                    } else if (mCommentList != null && mCommentList.size() > 0) {
                        //展示没有更多评论
                        isAutoLoadMore = false;
                        msg = "没有更多评论,点击重试";
                        type = 2;
                    } else {
                        mCommentAdapter.notifyDataSetChanged();
                        //展示暂无评论
                        isAutoLoadMore = false;
                        type = 3;
                    }
                } else {
                    //当前没有评论则显示加载错误
                    type = 2;
                }
                //解除刷新状态
                onComplete(type,msg);
            }
        });

    }


    /**
     * 增加评论
     */
    public void addComment(FilmComment filmComment) {
        if (mCommentList == null) {
            mCommentList = new ArrayList<FilmComment>();
        }
        if (mCommentList.size() == 0) {
            FilmComment comment = new FilmComment();
            comment.setCommentTypeName("评论");
            mCommentList.add(comment);
        }
        try {
//            mCommentList.add(addCommentIndex, filmComment);
            mCommentList.add( filmComment);
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mCommentAdapter == null) {
            mCommentAdapter = new FilmCommentAdapter(mCommentList, mActivity);
            setAdapter(mCommentAdapter);
        } else {
            mCommentAdapter.notifyDataSetChanged();
        }
        onComplete(1, "");
    }

    public boolean isRefreshing() {
        return isRefreshing;
    }

    public void setIsRefreshing(boolean isRefreshing) {
        this.isRefreshing = isRefreshing;
    }

    @Override
    public void onClick(View v) {
        if (v == null) {
            return;
        }
        //错误点击
        if (v.getId() == R.id.load_error_page) {
            loadCommentData();
        }
    }

    /**
     * 设置空数据时的点击
     *
     * @param onClickListener
     */
    public void setEmptyViewOnClickListener(OnClickListener onClickListener) {
        if (loadMoreView != null) {
            loadMoreView.setEmptyPageOnClickListener(onClickListener);
        }
    }


}
